package com.sks.web.action.house;

import java.io.IOException;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.codehaus.jackson.JsonFactory;
import org.codehaus.jackson.JsonGenerator;
import org.codehaus.jackson.map.ObjectMapper;
import org.springframework.stereotype.Controller;

import com.sks.bean.PageView;
import com.sks.bean.QueryResult;
import com.sks.bean.pojo.Favorites;
import com.sks.bean.pojo.House;
import com.sks.core.SystemConstants;
import com.sks.service.house.AreaService;
import com.sks.service.house.FavoritesService;
import com.sks.service.house.HouseService;
import com.sks.service.house.HouseTypeService;
import com.sks.service.house.PropertyTypeService;
import com.sks.utils.StringUtil;
import com.sks.utils.WebUtil;
import com.sks.web.action.BasicAction;
import com.sks.web.action.BuildHtmlFile;
import com.sks.web.formbean.house.HouseForm;

@Controller("/sks/house")
public class ClientHouseAction extends BasicAction {
   
   @Resource(name = "houseServiceBean") private HouseService service;
   @Resource(name = "houseTypeServiceBean") private HouseTypeService houseTypeService;
   @Resource(name = "areaServiceBean") private AreaService areaService;
   @Resource(name = "propertyTypeServiceBean") private PropertyTypeService propertyTypeService;
   @Resource(name = "favoritesServiceBean") private FavoritesService favoritiesService;
   //private static int PAGE_FIRSTINDEX = 1;
   
   public ActionForward list(ActionMapping mapping, ActionForm form,
         HttpServletRequest request, HttpServletResponse response)
         throws Exception {
	  setBaseData(request);
      HouseForm formbean = (HouseForm) form;
      StringBuffer sb = new StringBuffer(" o.houseStatus = '" + House.HOUSE_STATUS_PUBLISHED + "'");
      List params = new ArrayList();
      
      int firstindex = formbean.getChangeOrderBy() ? 1 : formbean.getPage();
      
      if (!StringUtil.isEmpty(formbean.getTitle())) {
    	  //formbean.setTitle(StringUtil.unescape(formbean.getTitle()));
    	  sb.append(" and o.title like ?");
		  params.add("%" + StringUtil.unescape(request.getParameter("keyWord")) + "%");
      }
      
      if (null != formbean.getMenuName()) {
    	  if ("houseListBuy".equals(formbean.getMenuName())) {
    		  sb.append(" and o.transaStatus in (?, 2)");
    		  params.add(1);
    	  } else if ("houseListRent".equals(formbean.getMenuName())) {
    		  sb.append(" and o.transaStatus in (?, 2)");
    		  params.add(0);
    	  }
    	  
    	  if (null != formbean.getMaxPrice() || null != formbean.getMinPrice()) {
        	  setPriceRange(formbean, sb, params);
        	  //firstindex = 1;
          }
      }
      
      if (null != formbean.getTopAreaId()) {
    	  if (null == formbean.getAreaId()) {
    		  sb.append(" and o.area.parentArea.areaId = ?");
        	  params.add(formbean.getTopAreaId());
    	  } else {
    		  sb.append(" and o.area.areaId = ?");
        	  params.add(formbean.getAreaId());
    	  }
    	  //firstindex = 1;
      }
      if (null != formbean.getHouseTypeId()) {
    	  sb.append(" and o.houseType.houseTypeId = ?");
    	  params.add(formbean.getHouseTypeId());
    	  //firstindex = 1;
      }
      if (null != formbean.getPropertyTypeId()) {
    	  sb.append(" and o.propertyType.propertyTypeId = ?");
    	  params.add(formbean.getPropertyTypeId());
    	  //firstindex = 1;
      }
      
      LinkedHashMap<String, String> orderby = new LinkedHashMap<String, String>();
      if (null != formbean.getOrderBy()) {
  		  String[] ss = formbean.getOrderBy().split("_");
  		  if (ss.length >= 2) {
  			  orderby.put(ss[0], ss[1]);
  		  }
      }
      orderby.put("isHot", "desc");
      
      PageView<House> pv = new PageView<House>(formbean.getPageSize(), firstindex);
      pv.setQueryResult(service.getScrollData(pv.getFirstResult(), pv.getMaxresult(), sb.toString(), params.toArray(), orderby));

      request.setAttribute(PAGEVIEW, pv);
      return mapping.findForward(LIST);
   }
   
	private void setPriceRange(HouseForm formbean, StringBuffer sb, List params) {
		if ("houseListBuy".equals(formbean.getMenuName())) {
			if (null != formbean.getMinPrice()) {
				sb.append(" and o.salePrice >= ?");
				params.add(Double.parseDouble(formbean.getMinPrice().toString()));
			}

			if (null != formbean.getMaxPrice()) {
				sb.append(" and o.salePrice < ?");
				params.add(Double.parseDouble(formbean.getMaxPrice().toString()));
			}
		} else if ("houseListRent".equals(formbean.getMenuName())) {
			if (null != formbean.getMinPrice()) {
				sb.append(" and o.rentPrice >= ?");
				params.add(Double.parseDouble(formbean.getMinPrice().toString()));
			}

			if (null != formbean.getMaxPrice()) {
				sb.append(" and o.rentPrice < ?");
				params.add(Double.parseDouble(formbean.getMaxPrice().toString()));
			}
		}
	}

   private void setBaseData(HttpServletRequest request) {
      request.setAttribute("houseTypes", houseTypeService.getScrollData().getResultlist());
      request.setAttribute("topAreas", areaService.findAreas(true, true));
      request.setAttribute("propertyTypes", propertyTypeService.getScrollData().getResultlist());
   }
   
	public ActionForward info(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) throws Exception {
		HouseForm formbean = (HouseForm) form;
		House house = service.find(formbean.getHouseId());
		if (WebUtil.getUsers(request) != null) { // 判断是否用户已登录,用于前台收藏功能
			List<Object> params = new ArrayList<Object>();
			request.setAttribute("user", WebUtil.getUsers(request).getUserId());
			StringBuffer sb = new StringBuffer(" o.user.userId = " + WebUtil.getUsers(request).getUserId());
			sb.append(" and o.house.houseId = ?");
			params.add(Integer.parseInt(request.getParameter("houseId")));
			PageView<Favorites> pv = new PageView<Favorites>(formbean.getPageSize(), 0);
			pv.setQueryResult(favoritiesService.getScrollData(0, pv.getMaxresult(), sb.toString(), params.toArray(), null));
			if(pv.getTotalrecord()>0){
				request.setAttribute("isCollected", true);
			}
		} else {
			request.setAttribute("user", "nobody");
		}
		if (null == house || !House.HOUSE_STATUS_PUBLISHED.equals(house.getHouseStatus())) {
			return mapping.findForward("noHouse");
		}
		
		request.setAttribute("house", house);
		history(house.getHouseId(), request);
		return mapping.findForward(INFO);
	}
	
	private void history(Integer houseId, HttpServletRequest request) {
		HttpSession session = request.getSession(true);
		List<Integer> hs = (List<Integer>) session.getAttribute(SystemConstants.SYS_HISTORY_HOUSE);
		if (null == hs) {
			hs = new ArrayList<Integer>();
		}
		if (!hs.contains(houseId)) {
			hs.add(houseId);
		}
		session.setAttribute(SystemConstants.SYS_HISTORY_HOUSE, hs);
	}
	
	public ActionForward history(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) throws Exception {
		/*StringBuffer sb = new StringBuffer("[");
		HttpSession session = request.getSession(true);
		List<Integer> hs = (List<Integer>) session.getAttribute(SystemConstants.SYS_HISTORY_HOUSE);
		StringBuffer p = new StringBuffer("select o " + "from House o where o.houseId in (");
		for (int i = 0; null != hs && i < hs.size(); i++) {
			if (i == 0) {
				p.append("?");
			} else {
				p.append(", ?");
			}
		}
		p.append(")");
		if(hs != null){
			List<House> houses = service.getListByJpql(p.toString(), hs.toArray());
		
			for (int i = 0; null != houses && i < houses.size(); i++) {
				House house = houses.get(i);
				List<UploadFile> imgs = uploadFileService.getHousePictures(house.getHouseId());
				String img = "";
				if (!CollectionUtils.isEmpty(imgs)) {
					img = imgs.get(0).getPath() + "/" + imgs.get(0).getName() + "." + imgs.get(0).getExtension();
				}
				if (i > 0) {
					sb.append(",");
				}
				sb.append("{'houseId':'" + house.getHouseId() + "',");
				sb.append("'building':'" + (null == house.getBuilding() ? "" : house.getBuilding().getName()) + "',");
				sb.append("'area':'"+(null == house.getArea() ? "" : house.getArea().getName())+"',");
				sb.append("'space':'"+house.getSpace()+"',");
				sb.append("'salePrice':'"+house.getSalePrice()+"',");
				sb.append("'rentPrice':'"+house.getRentPrice()+"',");
				sb.append("'transaStatus':'"+house.getTransaStatus()+"',");
				sb.append("'img':'"+img+"'");
				sb.append("}");
			}
		}
		sb.append("]");
		response.getWriter().print(sb.toString());*/
		String result = BuildHtmlFile.buildHouseHisotry(request);
		response.getWriter().print(result);
		return null;
	}
	//TODO
	/**
	 * 需要分开house是出租还是出售
	 */
	public ActionForward queryHouseList(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) throws IOException{
		int HOUSE_LIST_COUNT = 6;
		//获取指定buidlingId 的已经发布的房源，
		StringBuffer sb = new StringBuffer("1=1 and o.building.buildingId =?1 ");
		sb.append(" and o.houseStatus = '" + House.HOUSE_STATUS_PUBLISHED + "' ");
		
		List<Object> params = new ArrayList<Object>();
		HouseForm houseForm = (HouseForm) form;
		Integer buildingId = houseForm.getBuildingId();
		params.add(buildingId);
		
		LinkedHashMap<String, String> orderby = new LinkedHashMap<String, String>();
	      if (null != houseForm.getOrderBy()) {
	  		   //TODO
	      }
	    //transaStatus 0是出租，1是出售，2是租售均可
	      if(houseForm.getTransaStatus()!=null && houseForm.getTransaStatus()==0){
	    	  orderby.put("rentPrice", "desc");
	      }
	      orderby.put("salePrice", "desc");
	      
	//	int firstindex = houseForm.getChangeOrderBy() ? PAGE_FIRSTINDEX : houseForm.getPage();
	//	PageView<House> pv = new PageView<House>(houseForm.getPageSize(),firstindex );
		PageView<House> pv = new PageView<House>(HOUSE_LIST_COUNT,houseForm.getPage());
		
		QueryResult<House> m = service.getScrollData(pv.getFirstResult(),pv.getMaxresult(),  sb.toString(),
	 			 params.toArray(),orderby);
		
/*		QueryResult<House> m = service.getScrollData(-1, -1, sb.toString(),
				params.toArray());
*/		
		//System.out.println("result 的长度 ：" + m.getTotalrecord());
		StringWriter swt = new StringWriter();
		JsonGenerator gen = new JsonFactory().createJsonGenerator(swt);
		ObjectMapper objectMapper = new ObjectMapper();
		objectMapper.writeValue(gen, m.getResultlist());
		
		Map<Object, Object> resultMap = new HashMap<Object, Object>();
		resultMap.put("resultSet", swt.toString());
		resultMap.put("totalPages",Math.ceil(m.getTotalrecord()/HOUSE_LIST_COUNT));
		
		StringWriter swt2 = new StringWriter();
		JsonGenerator gen2 = new JsonFactory().createJsonGenerator(swt2);
		ObjectMapper objectMapper2 = new ObjectMapper();
		objectMapper2.writeValue(gen2, resultMap);
		
		response.getWriter().print(swt2.toString());
		
//		response.getWriter().print(swt.toString());
		swt=null;
		gen=null;
		objectMapper=null;
		return null;
	}
}
